import actionStaticRegistrar from "./ActionStaticRegistrar";
import FileUtil from "../../utils/FileUtil";
import path from "node:path";
import ignore from "ignore";
import fs from "node:fs";
import actionStaticPool from "./ActionStaticPool";

class ActionStaticLoader {
    load() {
        const staticPath = actionStaticRegistrar.staticPath
        if (!staticPath) {
            return;
        }
        if (!fs.existsSync(staticPath)) {
            console.error('static Path is not found.')
            return;
        }
        console.log('loading staticPath: ' + staticPath);
        FileUtil.getAllFileInDirectory(staticPath).then(files => {
            const filePaths = this.filterFilePath(files)
            if (filePaths.length === 0) {
                return
            }
            const pathMap: Record<string, string> = {}
            for (let filePath of filePaths) {
                const routePath = filePath.substring(staticPath.length).replace(/\\+/g, '/').replace(/\/+/g, '/');
                pathMap[routePath] = filePath
            }
            actionStaticPool.pathMap = pathMap
        })
    }

    private filterFilePath(filePathList: string[]): string[] {
        const resList = []
        const staticConfig = actionStaticRegistrar.staticConfig
        if (!staticConfig || Object.keys(staticConfig).length === 0) return filePathList
        const ig = ignore().add(staticConfig.ignores || [])
        for (let filePath of filePathList) {
            const fileType = path.extname(filePath)
            if (staticConfig.types && staticConfig.types.length > 0) {
                // 有类型时判断类型
                if (staticConfig.types.includes(fileType)) {
                    resList.push(filePath);
                }
            }
            if (staticConfig.ignoreTypes && staticConfig.ignoreTypes.length > 0) {
                // 有忽略类型时判断类型是否被忽略
                if (!staticConfig.ignoreTypes.includes(fileType)) {
                    resList.push(filePath);
                }
            }
            if (staticConfig.ignores && staticConfig.ignores.length > 0) {
                // 判断是否被忽略
                if (!ig.ignores(filePath)) {
                    resList.push(filePath);
                }
            }
            if (staticConfig.filter && typeof staticConfig.filter === "function") {
                // 执行过滤方法判断
                if (staticConfig.filter(filePath)) {
                    resList.push(filePath);
                }
            }
        }
        return resList;
    }
}

export default new ActionStaticLoader();
